import userService from 'SERVICE/userService'
import { message } from 'antd'
import API from 'UTIL/libs/api'
// ================================
// Action Type
// ================================
const LOG_IN = 'LOG_IN'
const LOG_ERR = 'LOG_ERR'
const LOG_OUT = 'LOG_OUT'

// ================================
// Action Creator
// ================================
const login = (users) => {
  let { userName, password } = users
  return dispatch => {
    API.callJson(`/admin/login?username=${userName}&password=${password}`)()
    .then((data)=>{
      dispatch({
        type: LOG_IN,
        payload: { login: true, ...data }
      })
      message.success('登录成功')
      location.href = '#/'
    })
    .catch((msg)=>{
      dispatch({
        type: LOG_ERR,
        payload: { login: false, msg: msg}
      })
      message.error('账户或密码错误')
    })
  }
}

const checkLogin = () => {
  return dispatch => {
    userService
      .checkLogin()
      .then((re) => {
        console.log(re)
        if (!re) return
        dispatch({
          type: LOG_IN,
          payload: { login: true, payload: re }
        })
      })
  }
}

const logout = () => {
  return dispatch => {
    userService
      .logout()
      .then(() =>
        dispatch({
          type: LOG_OUT
        })
      )
  }
}
/* default 导出所有 Actions Creator */
export default {
  login, checkLogin, logout
}

// ================================
// Action handlers for Reducer
// 本来更新 state 是 Reducer 的责任
// 但要把 ActionType 导出又引入实在太麻烦
// 且在 Reducer 中写 switch-case 实在太不优雅
// 故在此直接给出处理逻辑
// ================================
export const ACTION_HANDLERS = {
  [LOG_IN]: (userData, { payload }) => payload, // payload is userData
  [LOG_ERR]: (status, { payload }) => payload,
  [LOG_OUT]: () => null
}
